// 引入coolsite360交互配置设定
require('coolsite.config.js');

// import {WxUserManager} from '../../utils/wxUserManager';

import {
  envid,
  apiBaseUrl,
  roleDict,
} from '../../config.js'

// import {
//   setStorageFormUserInfoAndGopage
// } from '../../utils/who.js';

// 获取全局应用程序实例对象
var app = getApp();

//云开发的初始化
wx.cloud.init({
  env: envid,
  traceUser: true
});

var app = getApp();

// 创建页面实例对象
Page({
  /**
   * 页面名称
   */
  name: "index",
  /**
   * 页面的初始数据
   */

  data: {
    wxopenid: app.globalData.wxopenid,
    warmBgColor: app.globalData.warmBgColor,
    logo2ImageSrc: app.globalData.logo2ImageSrc,
    originImageSrc: app.globalData.originImageSrc,
    modalHidden: true,
    apiResJson: JSON.stringify({}),
    isShowUserInfoLayer: false,

    toBeSelectUserInfoDict: {
      // "ox-6X5F0urrzu-mruGM-AWauQ0OI": {
      //   "name": "sdf",
      //   "room": "101",
      //   "s_class": "1",
      //   "school": "计算机工程学院",
      //   "student_id": 200001000,
      //   "userid": 200001000,
      //   "wxopenid": "ox-6X5F0urrzu-mruGM-AWauQ0OI"
      // },
    },
  },

  radioChange(e) {
    console.log('59-59 radio发生change事件，携带value值为：', e.detail.value)

    const items = this.data.items
    // for (let i = 0, len = items.length; i < len; ++i) {
    Object.values(this.toBeSelectUserInfoDict).forEach(function (toSelecteUserInfo) {
      toSelecteUserInfo.checked = toSelecteUserInfo.value === e.detail.value
    });
    // }

    this.setData({
      items
    })
  },

  show: function () {
    // var showtxt = this.data.id + " " + this.data.pwd;
    this.setData({
      // txt: showtxt,
      // wxopenid,
      modalHidden: !this.data.modalHidden
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { // onLoad 钩子函数 才有 options 参数传入, 所以每次从 这个登录页面转到其他页面要销毁该页面，或者处理 this.data.needAuthedRedirect
    // const needAuthedRedirect = options.needAuthedRedirect ? true : false;
    // 注册coolsite360交互模块
    app.coolsite360.register(this);
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: getApp().globalData.warmBgColor,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    // 执行coolsite360交互组件展示
    // this.fetchUserInfoFromBackendFlow()
    // .then(userInfo => {
    //   return setStorageFormUserInfoAndGopage(userInfo)
    // })
    app.coolsite360.onShow(this);
    const wxopenid = app.globalData.wxopenid || wx.getStorageSync('wxopenid');
    // console.log(`76-76 hook:::::show:::wxopenid:`, wxopenid);
    this.setData({
      wxopenid
    })
    // const needAuthedRedirect = false;
    // this.wxAuth(null, needAuthedRedirect)

  },

  wxAuth(event = null, needAuthedRedirect = false) {
    const that = this;
    if (event) needAuthedRedirect = true; //如果是页面元素事件触发wxAuth方法就需要转跳，不然不转跳
    wx.cloud.callFunction({
      name: "getOpenid",
      success(res) {
        // that.setData({
        //   apiResJson: JSON.stringify(res)
        // })
        console.log(`99-99 method:::::wxAuth:::res: `, res);
        var wxopenid = res.result.openid;
        app.globalData.wxopenid = wxopenid;
        that.setData({
          wxopenid,
        });
        console.log('请求获取wxopenid:', wxopenid);
        wx.setStorageSync('wxopenid', wxopenid)
        // app._getUserInfo();
        that.fetchUserInfoFromBackendFlow(wxopenid, needAuthedRedirect)

      },
      fail(res) {

        wx.showToast({
          title: '微信授权异常,请检查网络并登录微信',
          icon: 'none',
        })
        // wx.navigateBack({
        //   delta: 1,
        // });
        // app._getUserInfo();
        // app.fetchUserInfoFromBackendFlow(wxopenid);
      }
    });
  },

  // 获取用户信息，如果用户没有授权，就获取不到
  fetchUserInfoFromBackendFlow(wxopenid, needAuthedRedirect = false) { //当前项目的Mypage 是 /page/*/five 模块, 该函数在该模块执行
    //从网络获取最新用户信息
    const that = this;
    const apiUrl = `${apiBaseUrl}/read_user_by_wxopenid?wxopenid=${wxopenid}`
    // return new Promise((resolve, reject) => {
    wx.request({
      url: apiUrl,
      method: 'GET',
      success: function (res) {
        console.log(`59-59 res: `, res, JSON.stringify(res));

        let userInfo = res.data;
        if (['no record', 'wild wxopenid'].includes(userInfo)) {
          userInfo = {}
        } else if (Object.prototype.toString.call(userInfo) != '[object Object]') {
          console.log('res.data as userInfo must is not special string “no record” or object... please check api...');
          return
        }
        console.log('请求获取userInfo成功', userInfo)
        const userInfoDict = wx.getStorageSync('userInfoDict') || {};
        console.log(`159-159 method:::::fetchUserInfoFromBackendFlow:::userInfoDict:`, userInfoDict);
        userInfoDict[wxopenid] = userInfo;
        wx.setStorageSync('userInfoDict', userInfoDict)

        if (JSON.stringify(userInfo) == JSON.stringify({}) || userInfo.role == null) {
          wx.navigateTo({
            url: '/page/userForm/userForm?wxopenid=' + wxopenid,
          })
        } else {
          if (needAuthedRedirect) {
            that.goMePageByRole(userInfo.role);
            // const userid = userInfo.userid;
            // let path;
            // if (userid.length == 6) {
            //   path = '/page/teacher/page/five/five';
            // } else {
            //   path = '/page/student/page/five/five';
            // }
            // wx.redirectTo({
            //   url: path,
            // })
          }

        }

        // resolve(userInfo);


        // var user = res.userInfo;
        // user.openid = app.globalData.openid;
        // app.globalData.userInfo = user;



        // app._saveUserInfo(user);
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        // if (app.userInfoReadyCallback) {
        //   app.userInfoReadyCallback(res)
        // }
      },
      fail: function (res) { //请求网络失败时，再读本地数据
        console.log(`144-144 fetchUserInfoFromBackendFlow:::function: 请求获取user失败,请检查backend apiUrl: ${apiUrl} 是否可以访问`)
        // var userStor = wx.getStorageSync('user');
        // var userInfo = storagerWxopenidAndUserInfo.syncGetValueByKey(wxopenid);
        // if (!userInfo) {
        //   reject('wild wxopenid');
        // } else {
        //   app.globalData.userInfo = userInfo;
        //   resolve(userInfo);
        // }

      }
    })
    // });

  },


  // readCachedUserInfoListFromStorage() {
  //   var cachedUserInfoDict = app.storagerWxopenidAndUserInfo.syncGetKvDict();
  //   const cachedUserInfoList = Object.values(cachedUserInfoDict);
  //   this.setData({
  //     cachedUserInfoList,
  //   });
  // },

  selectUserInfoFromStorage() {
    const userInfoDict = wx.getStorageSync('userInfoDict');
    if (Object.keys(userInfoDict).length === 0) {
      wx.showToast({
        title: '暂无历史登录记录',
        image: '/resources/icon_warning.png',
      })
    } else {
      this.setData({
        toBeSelectUserInfoDict: userInfoDict,
        isShowUserInfoLayer: true,
      });
    }

  },


  storageLogin(event) {
    const wxopenid = event.currentTarget.dataset.wxopenid;
    const role = event.currentTarget.dataset.role;
    console.log(`280-280 index/index.js method:::::storageLogin:::role==null, role:`, role==null,role);
    if (!wxopenid || role==null) {
      wx.showToast({
        title: '本地没有完备信息',
        icon: 'none',
      })
      return;
    }
    wx.setStorageSync('wxopenid', wxopenid)
    this.setData({
      wxopenid: wxopenid,
    })
    this.goMePageByRole(role);
  },

  goMePageByRole(role){
    let mePageUrl = `/page/${roleDict[role]['moduleName']}/page/five/five`;
    console.log(`292-292 teacher/page/five.js method:::::storageLogin::: mePageUrl: ${mePageUrl}`);
    wx.redirectTo({
      url: mePageUrl,
    })
  },

  closeSelection() {
    this.setData({
      isShowUserInfoLayer: false,
    });
  },

  // setStorageFormUserInfoAndGopage,

  // logoutSetStorage(wxopenid) {
  //   storagerWxopenidAndUserInfo.syncDropKvByKey(wxopenid);
  // },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },


  // //以下为自定义点击事件
  // goStudent: function () {
  //   wx.redirectTo({
  //     url: '../student/page/two/two',
  //   })
  //   wx.showToast({
  //     title: '登录成功',
  //     icon: 'success',
  //     duration: 3000
  //   })
  // },
  // goTeacher: function () {
  //   wx.redirectTo({
  //     url: '../teacher/page/one/one',
  //   })
  //   wx.showToast({
  //     title: '登录成功',
  //     icon: 'success',
  //     duration: 3000
  //   })
  // },
  // goClass: function () {
  //   wx.redirectTo({
  //     url: '../teacher/page/three/three',
  //   })
  //   wx.showToast({
  //     title: '登录成功',
  //     icon: 'success',
  //     duration: 3000
  //   })
  // },
  // fetchLoginFlow() {
  //   var that = this;
  //   wx.request({
  //     url: `${app.globalData.apiBaseUrl}/login`,

  //     data: {

  //     },
  //     header: {
  //       'content-type': 'application/json' // 默认值
  //     },
  //     method: "POST",
  //     success: function (res) {

  //     }
  //   })

  // },

  // submit: function () {
  //   var id = this.data.id;
  //   console.log(`138-138 submit function was invoked... id:${id}`);
  //   if (this.data.id == "") {
  //     this.setData({
  //       txt: "学号不能为空",
  //       modalHidden: !this.data.modalHidden
  //     })
  //     return;
  //   }

  //   app.globalData.anitShakeExecuteCallback(this.fetchLoginFlow, 300);

  // }
})